<template>
  <div class="search">
    <div class="header">
      <span class="iconfont iconjiantou2" @click="$router.back()"></span>
      <van-search
        v-model="userKey"
        placeholder="请输入搜索关键词"
        shape="round"
      >
      </van-search>
      <div @click="onSearch">搜索</div>
    </div>
    <div class="historyList">
      <h2>历史记录</h2>
      <div
        class="record"
        v-for="(value, index) in history"
        :key="index"
        @click="search(value)"
      >
        {{ value }}
      </div>
    </div>
    <div class="history">
      <h2>搜索结果</h2>
      <router-link
        :to="'/articleDetail/' + value.id"
        class="record"
        v-for="value in like"
        :key="value.id"
      >
        {{ value.title }}</router-link
      >
    </div>
  </div>
</template>

<script>
import { post_search } from "@/apis/post.js";
export default {
  data() {
    return {
      userKey: "",
      like: [],
      history: [],
    };
  },
  activated() {
    this.history = JSON.parse(localStorage.getItem("history")) || [];
    this.userKey = "";
    this.history = [];
  },
  methods: {
    search(value) {
      this.userKey = value;
      this.onSearch();
      this.history = this.history.splice(10, 1);
    },
    async onSearch() {
      if (this.userKey.trim().length == 0) {
        this.toast.fail("请输入搜索内容");
      } else {
        let index = this.history.indexOf(this.userKey);
        if (index != -1) {
          this.history.splice(index, 1);
        }
        let res = await post_search(this.userKey);
        this.like = res.data.data;
        this.history.unshift(this.userKey);
        localStorage.setItem("history", JSON.stringify(this.history));
      }
    },
  },
};
</script>

<style lang='less' scoped>
.header {
  display: flex;
  height: 50px;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  border-bottom: 1px solid #ccc;
  .van-search {
    flex: 1;
    padding: 5px 12px;
  }
}
.history,
.historyList {
  padding: 10px;
  border-bottom: 1px solid #ccc;
  .record {
    display: inline-block;
    line-height: 26px;
    width: 45%;
    font-size: 14px;
    color: #666;
    margin-right: 5%;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    border-bottom: 1px dashed #ccc;
  }
  h2 {
    line-height: 40px;
    font-weight: bold;
  }
  > a {
    display: block;
    text-decoration: underline;
    line-height: 30px;
    color: #666;
  }
}
</style>